package com.changgou.search.controller;

import com.changgou.entity.Page;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

/**
 * @Author: 陈安
 * @Date: 2020/12/11$ 12:45$
 * @Description: $todo$
 * @Version 1.0
 */
@Controller
@RequestMapping("/search")
public class SearchController {
    @Autowired
    private SearchService searchService;

    @GetMapping("/list")
    public String list(@RequestParam Map<String,String> searchMap,Model model){

        //特殊符号处理
        this.handlerSearchMap(searchMap);

        //获取查询结果数据
        Map resultMap = searchService.search(searchMap);
        model.addAttribute("result",resultMap);
        model.addAttribute("searchMap",searchMap);

        //封装分页数据
        //1:总记录数,2:当前页 3:每页显示多少条
        Page<SkuInfo> page=new Page<SkuInfo>(
                Long.parseLong((String) resultMap.get("total")),
                Integer.parseInt((String) resultMap.get("pageNum")),
                Page.pageSize);
        model.addAttribute("page",page);




        //拼装url
        StringBuilder url = new StringBuilder("/search/list");
        if(searchMap!=null && searchMap.size()>0){
            url.append("?");
            for (String s : searchMap.keySet()) {
                if(!"sortRole".equals(s) && !"sortField".equals(s) && !"pageNum".equals(s)){
                    url.append(s).append("=").append(searchMap.get(s)).append("&");
                }
            }
            String s = url.toString();
            //去除路径上的最后一个&
            String substring = s.substring(0, url.length() - 1);
            model.addAttribute("url",substring);

        }else{
            //没有查询的条件,那就是最原始的查询就行了
            model.addAttribute("url",url);
        }


        return "search";
    }

    @GetMapping
    @ResponseBody
    public Map search(@RequestParam Map<String, String> searchMap) {
        //特殊符号处理
        handlerSearchMap(searchMap);
        Map search = searchService.search(searchMap);
        return search;
    }

    //对搜索入参带有特殊符号进行处理
    public void handlerSearchMap(Map<String,String> searchMap) {

        if (null != searchMap) {
            Set<Map.Entry<String, String>> entries = searchMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                if (entry.getKey().startsWith("spec_")) {
                    searchMap.put(entry.getKey(), entry.getValue().replace("+", "%2B"));
                }
            }
        }
    }

}
